package com.lu.netty.impl

import androidx.annotation.IntRange
import com.lu.netty.data.DataType
import com.lu.netty.data.NettyMessageVo
import com.lu.netty.io.client.ANettyClient
import com.lu.netty.io.core.NettyConnector
import com.lu.netty.io.core.NettyLog
import com.lu.netty.io.dispatcher.INettyClientListener
import io.netty.channel.Channel

/**
 * FileName : BaseNettyClient
 * Author : luqihua
 * Date : 2024/12/18
 * Desc :
 **/

class BaseNettyClient(
    ip: String,
    @IntRange(from = 1000, to = 65535)
    port: Int,
) : ANettyClient(ip, port) {
    companion object {
        private const val TAG = "BaseNettyClient"
    }

    private var listener: INettyClientListener? = null

    override fun onMessageArrived(channel: Channel, message: String) {
        val nettyConnector = NettyConnector(channel)
        try {
            val messageVo = NettyMessageVo.fromJson(message) ?: return
            when (messageVo.dataType) {
                DataType.CONTENT -> listener?.onContent(nettyConnector, messageVo)
                else -> listener?.onOther(nettyConnector, messageVo)
            }
        } catch (e: Exception) {
            NettyLog.e(TAG, "onMessageArrived : ", e)
        }
    }

    override fun getHeartbeat(): String {
        val heartbeatContent = listener?.getHeartbeat() ?: ""
        val messageVo = NettyMessageVo(dataType = DataType.HEARTBEAT, message = heartbeatContent)
        return messageVo.toJson()
    }

    fun setListener(listener: INettyClientListener) {
        this.listener = listener
    }

    override fun send(message: String) {
        super.send(NettyMessageVo.createContent(message).toJson())
    }
}